import 'package:pointycastle/export.dart' hide Signer, RSASigner;
import 'package:encrypt/encrypt.dart';
import 'package:encrypt/encrypt_io.dart';
import 'yl_base64_encrypt.dart';

class YLRSAEncrypt {
  // 单例
  static YLRSAEncrypt get instance => _instanceBase();
  static YLRSAEncrypt? _manager;
  static YLRSAEncrypt _instanceBase() {
    _manager ??= YLRSAEncrypt();
    return _manager!;
  }

  Encrypter? _encrypter;
  String encrypter(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.encrypt(value).base64;
    }
    return value;
  }

  String decrypter(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.decrypt64(value);
    }
    return value;
  }

  String encrypter16(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.encrypt(value).base64;
    }
    return value;
  }

  String decrypter16(String value) {
    if (_encrypter != null && value.isNotEmpty) {
      return _encrypter!.decrypt16(value);
    }
    return value;
  }

  Future setEncryptKey({String? publicFile, String? privateFile}) async {
    if ((publicFile ?? '').isNotEmpty && (privateFile ?? '').isNotEmpty) {
      final publicKey = await parseKeyFromFile<RSAPublicKey>(publicFile!);
      final privateKey = await parseKeyFromFile<RSAPrivateKey>(privateFile!);
      _encrypter = Encrypter(RSA(
        publicKey: publicKey,
        privateKey: privateKey,
      ));
    } else {
      final parser = RSAKeyParser();

      final publicKey = parser
          .parse(YLBase64Encrypt.decodeBase64(base64publickey)) as RSAPublicKey;
      final privateKey = parser
          .parse(YLBase64Encrypt.decodeBase64(base64privatek)) as RSAPrivateKey;
      _encrypter = Encrypter(RSA(
        publicKey: publicKey,
        privateKey: privateKey,
      ));
    }
  }

  String get base64publickey =>
      'LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlHZU1BMEdDU3FHU0liM0RRRUJBUVVBQTRHTUFEQ0JpQUtCZ0hTNkdWdVRXSGRrWHBkY0ZCVnB3aE8zUmVwMQpVbktRcThlTXVwMXdVM0RNbXJmZFl3eFRxRWE1RGpod0ZmZUtSVl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